package com.gzu.shop.controller;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.gzu.shop.base.BaseController;
import com.gzu.shop.common.Result;
import com.gzu.shop.constant.JwtClaimsConstant;
import com.gzu.shop.context.BaseContext;
import com.gzu.shop.entity.Comment;
import com.gzu.shop.entity.User;
import com.gzu.shop.mapper.CommentMapper;
import com.gzu.shop.mapper.UserMapper;
import com.gzu.shop.param.SearchCondition;
import com.gzu.shop.service.CommentService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

/**
 * @author Clown
 */
@RestController
@RequestMapping("/comment")
@AllArgsConstructor
@Slf4j
@Tag(name = "评论相关接口")
public class CommentController extends BaseController<CommentService, Comment> {
    private CommentMapper commentMapper;
    private UserMapper userMapper;
    @Override
    @Operation(description = "重写了父类方法，填充非数据库字段")
    @PostMapping("/page/{startPage}/{pageSize}")
    public Result<IPage<Comment>> page(@PathVariable int startPage,
                                       @PathVariable int pageSize,
                                       @RequestBody SearchCondition<Comment> searchCondition) {

        System.out.println(searchCondition);
        // 获取评论基本数据
        Result<IPage<Comment>> page = super.page(startPage, pageSize, searchCondition);

//        System.out.println("#############");
//        System.out.println(page.getData().getRecords());

        // 获取数据库字段
        List<Comment> records = page.getData().getRecords();

        // 填充非数据库字段
        for (Comment comment : records) {
            User user = userMapper.selectById(comment.getUserId());
            if (ObjectUtil.isNotEmpty(user)) {
                comment.setUsername(user.getUsername());
            }

//            comment.setUsername();
        }

        page.getData().setRecords(records);

        return page;
    }

    @Override
    @Operation(summary = "重写了父类方法,实现添加功能")
    @PostMapping("/add")
    public Result<Void> addEntity(@RequestBody Comment comment) {
        // 填充基本属性
        comment.setCommentTime(String.valueOf(System.currentTimeMillis()));
        comment.setUpdateTime(String.valueOf(System.currentTimeMillis()));
        comment.setLikeCount(String.valueOf(0));
        // 获取用户ID
        Map<String, Object> threadLocal = BaseContext.getThreadLocal();
        Integer userId = (Integer) threadLocal.get(JwtClaimsConstant.USER_ID);

        // 设置用户ID
        comment.setUserId(String.valueOf(userId));

//        System.out.println("#############");
        System.out.println(comment);
        return super.addEntity(comment);
    }
}
